package com.yuzi.model.systemMo;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.yuzi.model.BaseMo.BaseModel;

import java.util.List;

public class SysRole extends BaseModel<SysRole> {

	public Page<Record> findAllSysRole(int pageNumber, int pageSize, String roleName) {
		String select = "select sr.id,sr.name,sr.code,sr.status,sr.note,sd.name statusDes ";
		StringBuffer sqlExceptSelect = new StringBuffer(" from sys_role sr ");
		sqlExceptSelect.append("left join sys_dict sd on sd.pcode = 'roleStatus' and sr.status = sd.code WHERE 1=1 ");
		if (roleName != null && !roleName.equals("")) {
			sqlExceptSelect.append("and sr.name like CONCAT('%','" + roleName + "','%') ");
		}
		sqlExceptSelect.append("order by id");
		Page<Record> sysRolePage = Db.paginate(pageNumber, pageSize, false, select, sqlExceptSelect.toString());
		return sysRolePage;
	}

    public int addSysRole(SysRole sysRole){
        int maxIndex = getMaxIndex(this);
        boolean isSuc = sysRole.set("id",maxIndex+1).save();
        if (isSuc){
            return sysRole.getInt("id");
        }else
            return 0;
    }

    public List<SysRole> findSysRoleByCondition(String status){
        String sql = "select * from sys_role where 1 = 1 ";
         if (status != null)
             sql += "status = " + status;
        sql += "order by id ";
        return this.find(sql);
    }

    public boolean updateSysRole(SysRole sysRole){
        return sysRole.update();
    }

    public SysRole findSysRoleByUserId(Integer userId){
	    String sql = "SELECT sr.* FROM sys_role sr \n" +
                "\tINNER JOIN sys_user_role sur ON sr.id = sur.role_id\n" +
                "\tWHERE sur.user_id = ?";
	    return this.findFirst(sql,userId);
    }
}
